package lc20240515;

import java.util.HashMap;
import java.util.Map;

//矩阵置零
public class Demo2 {
    public static void main(String[] args) {
        int[][] matrix = {{1, 0, 3,0}, {4, 5, 6,7}, {0, 8, 9,2}};
//        int[][] matrix={
//                {1},
//                {0}
//        };
        setZeroes(matrix);
        printMatrix(matrix);
    }

    public static void setZeroes(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;

        //用两个集合记录哪些行，哪些列置零。
        Map<Integer,Boolean> colMap=new HashMap<>();
        Map<Integer,Boolean> rowMap=new HashMap<>();

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] == 0) {
                    rowMap.put(i,true);
                    colMap.put(j,true);
                }
            }
        }
        //给行置零
        for (int i = 0; i < row; i++) {
            if (rowMap.containsKey(i)){
                int k=0;
                while (k<matrix[i].length){
                    matrix[i][k]=0;
                    k++;
                }
            }
        }
        //给列置零
        for (int i = 0; i < col; i++) {
            if (colMap.containsKey(i)){
                int k=0;
                while (k<row){
                    matrix[k][i]=0;
                    k++;
                }
            }
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();  // 换行
        }
    }
}